import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { Session } from "@/utils/storage";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/index",
    name: "Index",
    component: () => import("@/views/index/index.vue"),
  },
  {
    path: "/",
    name: "/",
    redirect: "/login",
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由加载前
router.beforeEach((to, from, next) => {
  const token = Session.get("token");
  if (to.path === "/login" && !token) {
    next();
  } else {
    if (!token) {
      Session.clear();
      next(`/login`);
    } else if (token && to.path === "/login") {
      next("/index");
    } else {
      next();
    }
  }
});

export default router;
